// pages/store/shopping/index.js
import {
  getStoreCartApi,
  putStoreCartApi,
  deleteStoreCartApi,
  postStoreOrderApi
} from '../../../https/store'
import {
  BASE_URL
} from '../../../constant/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    BASE_URL,
    isSelectAll: false,
    totalPrice: 0,
    selectNum: 0,
    total: 0,
    cartList: [],
    addressList: [],
    address: {},
    notes: '',
    showAddress: false,
    showOrder: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getCartList()
    this.getAddress()
    this.setData({
      address: this.data.addressList[0]
    })
  },
  onShow() {
    console.log(13)
    this.getAddress()
  },
  // 获取收货地址
  getAddress() {
    const addressList = wx.getStorageSync('cardAddress') || []
    console.log(addressList)
    this.setData({
      addressList
    })
  },
  // 计算底部数据
  compute() {
    const cartList = this.data.cartList
    const total = this.data.total

    let selectNum = 0
    let totalPrice = 0
    cartList.forEach(item => {
      const price = item.store.price
      const select = item.select
      const numbert = item.number
      if (select) {
        totalPrice += (numbert * price)
        selectNum++
      }
    })

    this.setData({
      totalPrice,
      selectNum,
      isSelectAll: selectNum === total
    })
  },
  // 显示收货地址
  showAddAddress() {
    this.setData({
      showOrder: false,
      showAddress: true
    })
  },
  // 切换收货地址
  toggleAddress(e) {
    console.log(e)
    const docid = e.currentTarget.dataset.docid
    console.log(this.data.addressList)
    const addressList = this.data.addressList
    const newAddress = addressList.map((item) => {
      if (item.id == docid) {
        item.select = true
      } else {
        item.select = false
      }
      return item
    })
    console.log(newAddress)
    wx.setStorageSync('cardAddress', newAddress)

    this.getAddress()
  },
  // 删除收货地址
  async deleteAddress(e) {
    const {
      cancel
    } = await wx.showModal({
      title: '提示',
      content: '是否删除该收货地址',

    })
    if (cancel) return

    const docid = e.currentTarget.dataset.docid
    const addressList = this.data.addressList
    const newAddress = addressList.filter((item) => {

      return item.id != docid
    })
    console.log(newAddress)
    wx.setStorageSync('cardAddress', newAddress)
    this.getAddress()
  },
  // 选择收货地址
  selectAdderess(e) {
    console.log(this.data.addressList)
    const address = this.data.addressList.filter(item => item.select)
    console.log(address)
    if (!address[0]) {
      wx.showToast({
        title: '请添加收货地址',
        icon: 'none'
      })
      return
    }
    this.setData({
      address: address[0],
      showAddress: false,
      showOrder: true
    })
  },
  // 获取购物车列表
  async getCartList() {
    const getRes = await getStoreCartApi()
    if (getRes.code == 200) {
      this.setData({
        cartList: getRes.data.list,
        total: getRes.data.total
      })
      console.log(getRes.data)
    }
    this.compute()
  },
  // 切换数量
  async toggleCart(e) {
    const number = e.currentTarget.dataset.number
    const id = e.currentTarget.dataset.id
    const select = e.currentTarget.dataset.select
    const putRes = await putStoreCartApi({
      cartId: id,
      number,
      select
    })
    this.getCartList()
  },
  // 关闭购买弹框
  onClose() {
    this.setData({
      showOrder: false,
      showAddress: false
    })
  },
  // 打开结算弹框
  openShowOrder() {
    if (this.data.totalPrice > 0) {
      this.setData({
        showOrder: true
      })
    }

  },
  // 全选按钮
  async onChange(event) {
    console.log(1)
    wx.showLoading()
    const ids = this.data.cartList.map(item => item.id)
    for (let i = 0; i < ids.length; i++) {
      const putRes = await putStoreCartApi({
        cartId: ids[i],
        number: 0,
        select: event.detail
      })
    }
    this.setData({
      isSelectAll: event.detail,
    });
    wx.hideLoading()
    this.getCartList()
  },
  // 创建订单
  async createOrder() {
    console.log('创建订单')

    const {
      cartList,
      notes,
      address
    } = this.data
    console.log(address)
    if (!address) {
      wx.showToast({
        title: '请填写配送地址',
        icon: 'none'
      })
      return
    }
    console.log(this.data)
    const filterItem = cartList.filter(item => item.select)
    const cartIds = filterItem.map(item => item.id)
    const storeId = ""
    delete address.select
    delete address.id
    console.log(address)
    wx.showLoading({
      title: '创建订单中..',
      mask: true
    })
    const postRes = await postStoreOrderApi({
      cartIds,
      storeId,
      address,
      notes
    })
    console.log(postRes)

    if (postRes.code == 200) {
      setTimeout(() => {
        wx.hideLoading()
        wx.navigateTo({
          url: '../order/index?docid=' + postRes.data.id,
        })
        // 关闭弹框
        this.onClose()
        this.getCartList()
      }, 1200)
    } else {
      wx.showToast({
        title: '创建订单失败',
        icon: 'error'
      })
    }
  },
  // 删除购物车
  async deleteCart(e) {
    console.log(e)
    const {
      position,
      instance,
      name
    } = e.detail;
    const {
      cancel
    } = await wx.showModal({
      title: '提示',
      content: '是否确认删除购物车？',
    })
    console.log(cancel)
    instance.close()

    if (cancel) return
    wx.showLoading({
      title: '删除中...',
    })
    const deleteRes = await deleteStoreCartApi({
      cartId: name
    })
    console.log(deleteRes)
    if (deleteRes.code == 200) {
      wx.showToast({
        title: '删除成功',
      })

      this.getCartList()


    }

  },

  // 跳转添加购物地址页面
  gotoAddAddress() {
    wx.navigateTo({
      url: '../addAddress/index',
    })
  }
})